package com.mangatta.ec2.adaptor;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.*;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.androidplot.Plot;
import com.androidplot.series.XYSeries;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYStepMode;
import com.mangatta.cloud.Metric;
import com.mangatta.cloud.alarm.AlarmConfiguration;
import com.mangatta.cloud.dao.DbHelper;
import com.mangatta.cloud.dao.InstanceStatusDao;
import com.mangatta.ec2.activity.R;

import java.text.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AlarmConfigurationAdaptor extends ArrayAdapter<AlarmConfiguration> {
    private final static String TAG = AlarmConfigurationAdaptor.class.getSimpleName();

    private final Activity activity;
    private final List<AlarmConfiguration> alarmConfigurations;

    public AlarmConfigurationAdaptor(Activity activity, List<AlarmConfiguration> alarmConfigurations) {
        super(activity, R.layout.alarm_configuration_row, alarmConfigurations);
        this.activity = activity;
        this.alarmConfigurations = alarmConfigurations;
    }

    @Override
    public View getView(int position, View rowView, ViewGroup parent) {
        AlarmConfigurationView viewHolder;
        if (rowView == null) {
            LayoutInflater layoutInflater = activity.getLayoutInflater();
            rowView = layoutInflater.inflate(R.layout.alarm_configuration_row, null);
            Log.d(TAG, "Created view");
            viewHolder = new AlarmConfigurationView();
            viewHolder.alarmName = (TextView) rowView.findViewById(R.id.alarm_name);
            viewHolder.alarmUnitName = (TextView) rowView.findViewById(R.id.alarm_unit);
            viewHolder.threshold = (TextView) rowView.findViewById(R.id.alarm_threshold);
            viewHolder.graph = (ImageView) rowView.findViewById(R.id.graph);
            rowView.setTag(viewHolder);
        } else {
            viewHolder = (AlarmConfigurationView) rowView.getTag();
        }
        AlarmConfiguration alarmConfig = alarmConfigurations.get(position);
        viewHolder.alarmName.setText(alarmConfig.getDisplayName());
        viewHolder.alarmUnitName.setText(alarmConfig.getUnit());
        viewHolder.graph.setOnClickListener(new GraphPopupDisplayer(activity, alarmConfig.getInstance(), alarmConfig.getMetric()));

        if (alarmConfig.getThreshold() != null) {
            viewHolder.threshold.setText(alarmConfig.getThreshold().toString());
        }

        Log.d(TAG, "Row view for alarm" + alarmConfig);
        return rowView;
    }

    private static class GraphPopupDisplayer implements android.view.View.OnClickListener {
        private final String instanceId;
        private final Metric metric;
        private final Context context;
        private final InstanceStatusDao instanceStatusDao;
        private Dialog dialog;
        private XYPlot mySimpleXYPlot;
        private LineAndPointFormatter formatter;

        private GraphPopupDisplayer(Context context, String instanceId, Metric metric) {
            this.context = context;
            this.instanceId = instanceId;
            this.metric = metric;
            instanceStatusDao = new InstanceStatusDao(context);
        }

        public void onClick(View view) {
            setupDialog();
            List<Number> metricValues = new ArrayList<Number>();
            List<Number> timestamps = new ArrayList<Number>();

            SQLiteDatabase database = null;
            Cursor cursor = null;
            try {
                database = instanceStatusDao.getReadableDatabase();
                cursor = database.query(DbHelper.InstanceStatusTable.TABLE_INSTANCE_STATUSES, null,
                        DbHelper.InstanceStatusTable.C_INSTANCE + "=? AND " + DbHelper.InstanceStatusTable.C_METRIC + "=?",
                        new String[]{instanceId, metric.getName()}, null, null, null, "100");
                while (cursor.moveToNext()) {
                    Double metricValue = cursor.getDouble(cursor.getColumnIndex(DbHelper.InstanceStatusTable.C_VALUE));
                    metricValues.add(metricValue);
                    long timestamp = cursor.getLong(cursor.getColumnIndex(DbHelper.InstanceStatusTable.C_SAMPLED_AT));
                    timestamps.add(timestamp);
                }
                // TODO: Handle empty case
                XYSeries series2 = new SimpleXYSeries(timestamps, metricValues, instanceId + " " + metric.getDisplayName());
                mySimpleXYPlot.addSeries(series2, formatter);
                mySimpleXYPlot.setDomainStep(XYStepMode.SUBDIVIDE, 6);

            } finally {
                if (cursor != null && !cursor.isClosed()) {
                    cursor.close();
                }
                if (database != null) {
                    database.close();
                }
            }

            dialog.show();
        }

        private void setupDialog() {
            dialog = new Dialog(context);
            dialog.setContentView(R.layout.graph_popup);
            dialog.setTitle(String.format("%s - %s", instanceId, metric.getName()));
            dialog.setCancelable(true);

            mySimpleXYPlot = (XYPlot) dialog.findViewById(R.id.graph_box);
            mySimpleXYPlot.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);
            mySimpleXYPlot.getGraphWidget().getGridLinePaint().setColor(Color.BLACK);
            mySimpleXYPlot.getGraphWidget().getGridLinePaint().setPathEffect(new DashPathEffect(new float[]{1, 1}, 1));
            mySimpleXYPlot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK);
            mySimpleXYPlot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK);

            mySimpleXYPlot.setBorderStyle(Plot.BorderStyle.SQUARE, null, null);
            mySimpleXYPlot.getBorderPaint().setStrokeWidth(1);
            mySimpleXYPlot.getBorderPaint().setAntiAlias(false);
            mySimpleXYPlot.getBorderPaint().setColor(Color.WHITE);

            // setup our line fill paint to be a slightly transparent gradient:
            Paint lineFill = new Paint();
            lineFill.setAlpha(200);
            lineFill.setShader(new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.GREEN, Shader.TileMode.MIRROR));

            formatter = new LineAndPointFormatter(Color.rgb(0, 0, 0), Color.BLUE, Color.RED);
            formatter.setFillPaint(lineFill);
            mySimpleXYPlot.getGraphWidget().setPaddingRight(2);
            // customize our domain/range labels
            mySimpleXYPlot.setDomainLabel("Hours");
            mySimpleXYPlot.setRangeLabel(metric.getDisplayName());

            // get rid of decimal points in our range labels:
            mySimpleXYPlot.setRangeValueFormat(new DecimalFormat("0"));
            mySimpleXYPlot.setDomainValueFormat(new MyDateFormat());

            // by default, AndroidPlot displays developer guides to aid in laying out your plot.
            // To get rid of them call disableAllMarkup():
            mySimpleXYPlot.disableAllMarkup();

            Button button = (Button) dialog.findViewById(R.id.graph_close);
            button.setOnClickListener(
                    new android.view.View.OnClickListener() {
                        public void onClick(View view) {
                            dialog.dismiss();
                        }
                    }
            );
        }
    }

    private static class MyDateFormat extends Format {
        private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");

        @Override
        public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
            long timestamp = ((Number) obj).longValue();
            Date date = new Date(timestamp);
            return dateFormat.format(date, toAppendTo, pos);
        }

        @Override
        public Object parseObject(String source, ParsePosition pos) {
            return null;
        }

    }
}
